import {
  formatSeconds
} from '../../../utils/util.js'

let app = getApp()
Page({
  data: {
    spinShow: false,
    score: 0,
    paperId: null,
    examPaperAnswerId: null,
    form: {},
    timer: null,
    doTime: 0,
    userInfo: null,
    remainTime: 0,
    remainTimeStr: null,
    modalShow: false,
    result: 0,
    timeOutShow: false,
    address: "未打开地理位置授权！",
    latitude: null,
    longitude: null,
    paper:null,
    questionItem: null // 试卷数据
  },
//保存答案方法
  selectAnswer(event) {
    // 处理选择改变事件的逻辑代码
    var paperId=wx.getStorageSync('paperid');
    var siteId=wx.getStorageSync('siteId');
    var token= wx.getStorageSync('token');
    var answer1 = event.detail.value;
    var subjectId=event.currentTarget.dataset.id;
    var eoExamineAnswer = {
      paperId: paperId,
      siteId: siteId,
      answer: answer1,
      subjectId: subjectId
    };
    //向后端发送请求
    wx.request({
      url: 'http://60.216.100.50:9006/ruoyi-api/examination/saveAnswer',
      method:"POST",
      header: {
        'Authorization': 'Bearer ' + token, // 在请求头中携带 token
        },
      data: eoExamineAnswer,
        success: function(res) {
          var data=res.data;
          console.log(data)
        },
        fail: function(err) {
          // 处理请求失败
          console.error(err);
        }
    })
  },

// 多选保存答案方法
selectAnswer1(event) {
  console.log("执行了selectAnswer1");
  console.log(event.detail.value);
  // 处理选择改变事件的逻辑代码
  var paperId = wx.getStorageSync('paperid');
  var siteId = wx.getStorageSync('siteId');
  var token = wx.getStorageSync('token');
  var answer1 = event.detail.value;
  var subjectId = event.currentTarget.dataset.id;
  
  // 将答案数组转换为逗号分隔的字符串形式
  var formattedAnswer = answer1.join(",");
  
  var eoExamineAnswer = {
    paperId: paperId,
    siteId: siteId,
    answer: formattedAnswer, // 使用转换后的答案字符串
    subjectId: subjectId
  };
  
  //向后端发送请求
  wx.request({
    url: 'http://60.216.100.50:9006/ruoyi-api/examination/saveAnswer',
    method: "POST",
    header: {
      'Authorization': 'Bearer ' + token, // 在请求头中携带 token
    },
    data: eoExamineAnswer,
    success: function(res) {
      var data = res.data;
      console.log(data);
    },
    fail: function(err) {
      // 处理请求失败
      console.error(err);
    }
  })
},

//提交表单方法
examSubmit(event) {
  // 处理选择改变事件的逻辑代码
  var paperId = wx.getStorageSync('paperid');
  var siteId = wx.getStorageSync('siteId');
  var token = wx.getStorageSync('token');
  var eoExaminePerson = {
    paperId: paperId,
    siteId: siteId,
  };
  // 弹出确认对话框
  wx.showModal({
    title: '提示',
    content: '确定要提交试卷吗？',
    success: function(res) {
      if (res.confirm) {
        // 用户点击确定，执行提交逻辑
        wx.request({
          url: 'http://60.216.100.50:9006/ruoyi-api/examination/finshExamination',
          method: "POST",
          header: {
            'Authorization': 'Bearer ' + token, // 在请求头中携带 token
          },
          data: eoExaminePerson,
          success: function(res) {
            var data = res.data;
            console.log(data);
            if (data.code==200) {
             // 在提交成功后执行其他逻辑
              wx.navigateBack({
                delta: 1, // 返回的页面数，如果是1表示返回上一个页面
              });
            }
          },
          fail: function(err) {
            // 处理请求失败
            console.error(err);
          }
        });
      } else if (res.cancel) {
        // 用户点击取消，继续答题逻辑
        console.log('用户取消提交，继续答题');
        // 执行其他继续答题的逻辑
      }
    }
  });
},

  onShow: function () {

  },

  onLoad: function (options) {
    var data = JSON.parse(decodeURIComponent(options.data)); // 解析传递的试题数据
    this.setData({
      paper: data, // 将试题数据设置到页面的data中
      questionItem:data.subjectList,
      remainTime: data.examineTime*60,
      remainTimeStr: formatSeconds(data.examineTime*60)
    });
    this.timeReduce();
    console.log(this.data.paper);
    console.log(this.data.paper.subjectList);

    wx.enableAlertBeforeUnload({
      message: '确认退出考试？退出考试将自动提交试卷！',
      success: res => {
        wx.vibrateShort({
          type: 'heavy'
        })
      },
      fail: err => {}
    });

    wx.onUserCaptureScreen(function (res) {
      wx.showModal({
        title: '提示',
        content: '严禁截屏，如有下次，自动提交试卷！'
      })
    });

    // let paperId = options.id
    // let _this = this
    // _this.setData({
    //   paperId: options.id,
    // });

    // wx.getLocation({
    //   type: 'wgs84',
    //   success(res) {
    //     const latitude = res.latitude
    //     const longitude = res.longitude
    //     _this.setData({
    //       latitude: res.latitude,
    //       longitude: res.longitude
    //     });
    //     wx.cloud.callFunction({
    //       config: {
    //         env: 'dabenben-jrvrn'
    //       },
    //       // 要调用的云函数名称
    //       name: 'getLocation',
    //       // 传递给云函数的参数
    //       data: {
    //         lat: latitude,
    //         lng: longitude
    //       },
    //       success: res => {
    //         console.log(res.result.result.address)
    //         _this.setData({
    //           address: res.result.result.address,
    //         });
    //       },
    //       fail: err => {
    //         console.log(err)
    //       },
    //     })
    //   },
    //   fail(){
    //     wx.showModal({
    //       title: '提示',
    //       content: '您拒绝位置信息，无法参与考试！请打开位置共享，方可参与考试！',
    //       success (res) {
    //         if (res.confirm) {
    //           wx.openSetting({
    //             success (res) {
    //               console.log(res.authSetting)
    //               wx.navigateTo({
    //                 url: '../../examPapers1/index',
    //               })
    //             }
    //           })
    //         } else if (res.cancel) {
    //           wx.navigateTo({
    //             url: '../../examPapers1/index',
    //           })
    //         }
    //         }
    //     })
    //   }
    // });
    // wx.getNetworkType({
    //     success(res) {
    //       const networkType = res.networkType
    //       if (networkType != "wifi") {
    //         wx.showModal({
    //           title: '提示',
    //           content: '当前网络为' + networkType + ',建议使用WIFI网络参与考试！'
    //         })
    //       }
    //     }
    //   }),
    //   wx.getSetting({
    //     success(res) {
    //       if (!res.authSetting['scope.userLocation']) {
    //         wx.authorize({
    //           scope: 'scope.userLocation',
    //           success() {
    //             console.log("获取授权位置信息成功！")
    //           }
    //         })
    //       }
    //     }
    //   });
    // app.formPost('/api/wx/student/user/current', null).then(res => {
    //   if (res.code == 1) {
    //     _this.setData({
    //       userInfo: res.response,
    //     });
    //   }
    // });
    // _this.setData({
    //     spinShow: true
    //   }),
    //   app.formPost('/api/wx/student/exampaper/select/' + paperId, null)
    //   .then(res => {
    //     _this.setData({
    //       spinShow: false,
    //       userInfo:app.globalData.userInfo,
    //       score: res.response.score
    //     });
    //     if (res.code === 1) {
    //       _this.setData({
    //         form: res.response,
    //         paperId: paperId,
    //         remainTime: res.response.suggestTime * 60
    //       });
    //       _this.timeReduce()
    //     }
    //   }).catch(e => {
    //     _this.setData({
    //       spinShow: false
    //     });
    //     app.message(e, 'error')
    //   })
  },

  timeReduce() {
    let _this = this
    let timer = setInterval(function () {
      let remainTime = _this.data.remainTime
      if (remainTime <= 0) {
        _this.timeOut()
      } else {
        _this.setData({
          remainTime: remainTime - 1,
          remainTimeStr: formatSeconds(remainTime),
          doTime: _this.data.doTime + 1
        });
      }
    }, 1000)
    _this.setData({
      timer: timer
    });
  },

  onUnload() {
    clearInterval(this.data.timer)
  },

  returnRecord() {
    // wx.reLaunch({
    //   url: '/pages/record/index',
    // });
    app.globalData.examPaperAnswerId = this.data.examPaperAnswerId,
      // app.globalData.userScore =  this.data.score,
      console.log("我要传输的ID是" + this.data.examPaperAnswerId),
      wx.navigateTo({
        url: '/packageF/exam/result/index?id=' + app.globalData.examPaperAnswerId,
      })
  },
  timeOut() {
    clearInterval(this.data.timer)
    this.setData({
      timeOutShow: true
    });
    wx.vibrateShort({
      type: 'heavy'
    })
  },
  formSubmit: function (e) {
    let _this = this
    if (this.data.timer) {
      clearInterval(this.data.timer)
    }
    wx.showLoading({
      title: '提交中',
      mask: true
    })
    e.detail.value.id = this.data.paperId
    e.detail.value.doTime = this.data.doTime
    e.detail.value.address = this.data.address
    e.detail.value.latitude = this.data.latitude
    e.detail.value.longitude = this.data.longitude
    let title = this.data.form.name
    app.formPost('/api/wx/student/exampaper/answer/answerSubmit', e.detail.value)
      .then(res => {
        if (res.code === 1) {
          _this.setData({
            modalShow: true,
            result: res.response.score,
            examPaperAnswerId: res.response.examPaperAnswerId
          });
          app.globalData.userScore = res.response.score
          let fenshu = res.response.score;
          console.log(fenshu);
          let userName = _this.data.userInfo.realName;
          console.log(userName);
          let paperScore = (_this.data.score * 0.6).toFixed();
          console.log(paperScore);
          let address = _this.data.address
          console.log(address)
          wx.cloud.callFunction({
            name: 'getOpenId'
          }).then(res => {
            console.log(res);
            let openid = res.result.openid
            console.log("获取openid成功！", openid)
            wx.cloud.callFunction({
              config: {
                env: 'dabenben-jrvrn'
              },
              // 要调用的云函数名称
              name: 'sendNewMsg',
              // 传递给云函数的参数
              data: {
                openid: openid,
                // theme:"本次考试"+jige+",有问题联系陈鹏！",
                theme: address,
                number: fenshu,
                title: title,
                username: userName,
                bukao: "本次考试及格分：" + paperScore + "分"
              },
              success: res => {
                console.log(res)
              },
              fail: err => {
                console.log(err)
              },
            })
          })
          wx.vibrateShort({
            type: 'medium'
          })
        } else {
          app.message(res.response, 'error')
        }
        wx.hideLoading()
      }).catch(e => {
        wx.hideLoading()
        app.message(e, 'error')
      })
  }
})